<template>
  <div class="app-container">
    <!-- 添加果园按钮 -->
    <el-button type="success" @click="showDrawer(false)" style="margin-bottom: 20px;">
      <i class="el-icon-plus"></i> 新增果园
    </el-button>

    <!-- 果园列表表格 -->
   <el-table :data="orchards" style="width: 100%" border>
    <el-table-column prop="name" label="果园名称" width="180"></el-table-column>
    <el-table-column prop="area" label="果园面积(亩)" width="180"></el-table-column>
    <el-table-column prop="cropType" label="种植品种"></el-table-column>
    <el-table-column prop="plantCount" label="种植数量(棵)"></el-table-column>
    <el-table-column prop="soilType" label="土壤类型"></el-table-column>
    <el-table-column prop="address" label="地址"></el-table-column>
    <el-table-column prop="plantingDate" label="种植日期"></el-table-column>
    <el-table-column prop="location" label="地理位置"></el-table-column>
      <!-- 新增创建人信息列 -->
    <el-table-column prop="createdBy" label="创建人"></el-table-column>
   <el-table-column label="操作" width="150">
    <template slot-scope="scope">
      <div class="button-group">
        <el-button @click="showDrawer(true, scope.row)" type="primary" size="small">编辑</el-button>
        <el-button type="danger" size="small" @click="handleDeleteConfirm(scope.row.id)">删除</el-button>
      </div>
    </template>
  </el-table-column>
  </el-table>


    <!-- 抽屉式组件 - 编辑/新增果园 -->
    <template>
    <el-drawer :title="drawerTitle" :visible.sync="drawerVisible" direction="rtl" size="40%" :before-close="handleClose">
      <el-form :model="form" label-width="100px" :rules="rules" ref="formRef">
        <el-form-item label="果园名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入果园名称"></el-input>
        </el-form-item>
        <el-form-item label="果园面积" prop="area">
          <el-input-number v-model="form.area" :precision="2" :step="0.1" :min="0" placeholder="请输入果园面积"></el-input-number>
        </el-form-item>
        <el-form-item label="种植品种" prop="cropType">
          <el-input v-model="form.cropType" placeholder="请输入种植品种"></el-input>
        </el-form-item>
        <el-form-item label="种植数量" prop="plantCount">
          <el-input-number v-model="form.plantCount" :min="0" placeholder="请输入种植数量"></el-input-number>
        </el-form-item>
        <el-form-item label="土壤类型" prop="soilType">
          <el-input v-model="form.soilType" placeholder="请输入土壤类型"></el-input>
        </el-form-item>
        <el-form-item label="果树地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入果树地址"></el-input>
        </el-form-item>
        <el-form-item label="种植日期" prop="plantingDate">
          <el-date-picker v-model="form.plantingDate" type="date" placeholder="选择日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="地理位置" prop="location">
          <el-input v-model="form.location" placeholder="请输入地理位置"></el-input>
        </el-form-item>
        <!-- <el-form-item label="创建人" prop="createdBy">
          <el-input v-model="form.createdBy" placeholder="请输入创建人ID"></el-input>
        </el-form-item> -->
      </el-form>
      <div class="drawer-footer">
        <el-button @click="drawerVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('formRef')">确 定</el-button>
      </div>
    </el-drawer>
  </template>

  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';

export default {


  data() {
   return {
      drawerVisible: false,
      drawerTitle: '',
      form: {
        // 初始化表单数据，确保键名与 JSON 数据一致
        name: '',
        area: '',
        cropType: '',
        plantCount: '',
        soilType: '',
        address: '',
        plantingDate: '',
        location: '',
        createdBy: ''
      },
      rules: {
        name: [{ required: true, message: '请输入果园名称', trigger: 'blur' }],
        area: [{ required: true, message: '请输入果园面积', trigger: 'blur' }],
        cropType: [{ required: true, message: '请输入种植品种', trigger: 'blur' }],
        plantCount: [{ required: true, message: '请输入种植数量', trigger: 'blur' }],
        soilType: [{ required: true, message: '请输入土壤类型', trigger: 'blur' }],
        address: [{ required: true, message: '请输入果树地址', trigger: 'blur' }],
        plantingDate: [{ required: true, message: '请选择种植日期', trigger: 'change' }],
        location: [{ required: true, message: '请输入地理位置', trigger: 'blur' }],
        createdBy: [{ required: true, message: '请输入创建人ID', trigger: 'blur' }]
      }
    };

  },
  computed: {
    ...mapState('orchardinfo', ['orchards'])
  },
  methods: {
    ...mapActions('orchardinfo', ['fetchOrchards']),
    showDrawer(isEdit, row = null) {
      console.log('showDrawer called with:', isEdit, row); // 调试信息
      if (isEdit && row) {
        this.drawerTitle = '编辑果园信息';
        this.form = { ...row }; // 深拷贝避免直接修改原始数据
        console.log('Form data:', this.form); // 调试信息
      } else {
        this.drawerTitle = '新增果园';
        this.form = {}; // 清空表单
      }
      this.drawerVisible = true;
    },
   async deleteOrchard(id) {
      try {
        // 假设这里调用的是 Vuex store 的 dispatch 方法来执行删除操作
        await this.$store.dispatch('orchardinfo/deleteOrchard', id);

        // 显示删除成功的消息
        this.$message({
          type: 'success',
          message: '删除成功!'
        });

        // 刷新果园列表以显示更新后的数据
        await this.$store.dispatch('fetchOrchards');
      } catch (error) {
        console.error('删除失败:', error);
        // 显示删除失败的消息
        // this.$message({
        //   type: 'error',
        //   message: '删除失败，请检查控制台日志'
        // });
      }
    },
    async submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          try {
            let message;
            if (this.form.id) {
              // 更新果园信息
              await this.$store.dispatch('orchardinfo/updateOrchard', { id: this.form.id, data: this.form });
              message = '更新成功!';
            } else {
              // 创建新的果园信息
              await this.$store.dispatch('orchardinfo/createOrchard', this.form);
              message = '创建成功!';
            }

            this.$message({
              type: 'success',
              message
            });

            // 关闭抽屉
            this.drawerVisible = false;

            // 刷新果园列表以显示更新后的数据
            await this.$store.dispatch('fetchOrchards');

            // 重置表单（如果需要）
            // 注意：如果您希望保留表单以便继续编辑，则不需要重置
            // this.form = {};
          } catch (error) {
            console.error('提交失败:', error);
            this.$message({
              type: 'error',
              message: '提交失败，请检查控制台日志'
            });
          }
        } else {
          console.log('表单验证失败');
          return false;
        }
      });
    },
    handleDeleteConfirm(id) {
      this.$confirm('确定要删除此果园信息吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteOrchard(id);
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => { });
    },
    fetchOrchards() {
      // 获取果园数据的 action
      this.$store.dispatch('orchardinfo/fetchOrchards');
    }
  },
  created() {
    this.fetchOrchards();
  }
};
</script>

<style scoped>
.app-container {
  padding: 20px;
  background-color: #f0f2f5;
}

.el-table {
  margin-top: 0px;
}

.el-button--success {
  background-color: #67c23a;
  border-color: #67c23a;
}

.el-button--primary {
  background-color: #409eff;
  border-color: #409eff;
}

.el-button--danger {
  background-color: #f56c6c;
  border-color: #f56c6c;
}

/* 操作按钮组样式 */
.button-group {
  display: flex;
  justify-content: flex-start; /* 左对齐按钮 */
  flex-wrap: nowrap;           /* 防止换行 */
}

.button-group .el-button {
  margin-right: 2px;            /* 按钮间有间隔 */
  padding: 8px 12px;            /* 统一的内边距 */
  min-width: 64px;              /* 设置最小宽度以保证两个字的按钮大小一致 */
  flex: none;                   /* 确保按钮不会根据可用空间伸缩 */
}

.button-group .el-button:last-child {
  margin-right: 0;              /* 最后一个按钮不需要右边距 */
}
.el-button+.el-button {
    margin-left: 0px;
}
/* 自定义抽屉底部样式 */
.drawer-footer {
  text-align: right;
  padding: 10px 20px 20px;
  border-top: 1px solid #dcdfe6;
}
</style>